package com.jalarbee.web.jsf.converter;

import java.math.BigDecimal;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import com.jalarbee.core.money.MonetaryAmount;
import com.jalarbee.web.jsf.util.ApplicationUtils;
import java.math.BigInteger;
import java.text.NumberFormat;

public class MonetaryAmountConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String string) {
        try {
            NumberFormat decimalFormat = NumberFormat.getInstance(ApplicationUtils.getApplicationLocale());
            decimalFormat.setMinimumFractionDigits(2);
            BigDecimal amount = new BigDecimal(decimalFormat.parse(string).doubleValue());
            MonetaryAmount monetaryAmount = new MonetaryAmount(ApplicationUtils.getApplicationCurrency(), amount);
            return monetaryAmount;
        } catch (Exception e) {
            throw new ConverterException(e);
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object object) {
        try {
            return object.toString();
        } catch (Exception e) {
            throw new ConverterException(e);
        }

    }
}
